import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Tree, Button, Modal, message, Popover, Spin } from 'antd';
import _ from 'lodash';
import accounting from 'accounting';
import 'moment/locale/zh-cn';
import { PrimaryC, PrimaryGhostC, TableC, ModalC, ContentPackage, InputNumberC, SelectC } from '../../../../../comps';
import styles from './sh.less';
import NewModal from '../../tools';
import { isZiGuanEvir, exportFile as exportFileFunc } from '../../../../../utils/commonFunc';
import EnterUserPool from './userPoolModel';
import upRed from '../../../../../assets/busi/securityMnt/out_arrow.png';
import downGreen from '../../../../../assets/busi/securityMnt/enter_arrow.png';
import QueryC from './query';
import { findValueByCode } from '../../../../../utils/utils';

const { confirm } = Modal;
@connect(({ couponPoolDefinitionM, couponPoolQueryM, couponPoolApprovalM, loading, globalM }) => ({
  couponPoolDefinitionM,
  couponPoolQueryM,
  couponPoolApprovalM,
  loading,
  globalM,
}))
@Form.create()
export default class Bond extends PureComponent {
  state = {
    isShow: false, // model框是否展示
    isUser: '', // 登录用户id
    selectedKeys: [], // 字段设置默认值
    comCode: [], // 交易场所转义内容
    selectName: [], // 券池名称下拉数据
    tableData: [], // 表格数据
    selectCol: [], // 字段设置内容
    getnewColumns: [], // 字段设置内容
    selectPoolName: [], // model框券池名称下拉数据
    selectPoolTag: [], // model框标签下拉数据和查询页的标签下拉数据
    formDate: {}, // 查询条件
    current: 1, // 当前页码
    pageSize: 10, // 每页展示数量
    total: '', // 数据总量
    assetType: '', // 判断是股债基页面
    isVisible: false, // 出池model是否展示
    visible: false, // 字段设置model是否展示
    columns: [], // 股债基渲染公共列表
    fixedColumns: [], // 股债基固定公共列表
    detailData: {}, // 传入出池model数据
    toolText: '', // 传入出池model数据
    title2: [], // 入用户池标签数据
    exportQuery: {}, // 导出/查询入参
    typeName: '', // 股债基汉字展示
    InpoolData: {}, // 入用户池model数据
    ziisShow: false, // 资管model框是否展示
    isZiGuan: false,
    zgModelData: {}, // 资管出入券池名称
    sortedInfo: {},
    order: '',
    sortData: undefined,
    inPoolWay: '', // 入池方式,
    securityPoolName: '', // 当前选择的券池名称
    rowId: '', // 当前编辑的数据
    rowType: '', // 当前编辑字段
    internalRatingData: [], // 内部评级下拉数据
  };

  componentDidMount() {
    const temp = isZiGuanEvir();
    const isZiGuan = !!temp; // 判断该页面是在资管被引入的，还是maat
    let lll = window.location.hash.split('?')[0];
    const index1 = lll.lastIndexOf('/');
    lll = lll.substring(index1 + 1, lll.length);
    const Users = localStorage.getItem('antd-pro-userId');
    const isUser = isZiGuan ? temp['iv-user'] : Users;

    this.setState({
      isUser,
      assetType: lll,
      isZiGuan,
    });
    this.chooseType(lll, isZiGuan, isUser);
    this.getSelectData(lll, isZiGuan);
  }

  changeInvestmentAmounts = (e, record) => {
    const copyTableData = _.cloneDeep(this.state.tableData);
    copyTableData.map((v) => {
      if (v.id === record.id) {
        v.investmentAmounts = e;
      }
    });
    this.setState({ tableData: copyTableData });
  };

  // 根据用户点击判断显示那个页面
  chooseType = (lll, isZiGuan, isUser) => {
    if (lll == 'bond') {
      this.props.dispatch({
        type: 'couponPoolApprovalM/getInternalRating',
        payload: {
          tenant: localStorage.getItem('antd-pro-userId'),
        },
        callback: (res) => {
          if (res) {
            this.setState({
              internalRatingData: res,
            });
          }
        },
      });
      this.publicColumns('债券', isUser, isZiGuan);
      this.setState({ typeName: '债券' });
    } else if (lll == 'stock') {
      this.publicColumns('股票', isUser);
      this.setState({ typeName: '股票' });
    } else {
      this.publicColumns('基金', isUser);
      this.setState({ typeName: '基金' });
    }
  };

  // 股债基公共columns
  publicColumns = (type, isUser, isZiGuan) => {
    const { sortedInfo } = this.state;
    const {
      globalM: {
        dataDictionary: { SECURITY_POOL_ITEM_JYSTYPE = [] },
      },
    } = this.props;
    let zgType;
    let operationWidth = 195;
    if (type == '债券') {
      zgType = 'bond';
      operationWidth = 260;
    }
    if (type == '股票') {
      zgType = 'stock';
    }

    const columns = [
      {
        title: `${type}代码`,
        dataIndex: 'stockCode',
        key: 'stockCode',
        width: 130,
        fixed: 'left',
        render: (text, record) => {
          return text ? text : '--';
        },
      },
      {
        title: `${type}简称`,
        dataIndex: 'stockName',
        key: 'stockName',
        fixed: 'left',
        width: 180,
        render: (text, record, index) => {
          return (
            <span title={text} style={{ display: 'inline-block', width: '155px', height: '16px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {text ? text : '--'}
            </span>
          );
        },
      },
      {
        title: '交易场所',
        dataIndex: 'exchangeCode',
        key: 'exchangeCode',
        width: 170,
        render: (text, record) => {
          return findValueByCode(text, SECURITY_POOL_ITEM_JYSTYPE);
        },
      },
      {
        title: '发行主体',
        dataIndex: 'company',
        key: 'company',
        width: 160,
        render: (text, record, index) => {
          return (
            <span title={text} style={{ display: 'inline-block', width: '150px', height: '16px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {text ? text : '--'}
            </span>
          );
        },
      },
      {
        title: '入池方式',
        dataIndex: 'inPoolWay',
        key: 'inPoolWay',
        width: 120,
        render: (text, record) => {
          return text ? (text == 'auto' ? '自动入池' : '手动入池') : '--';
        },
      },
      {
        title: '入池日期',
        dataIndex: 'effectiveDate',
        key: 'effectiveDate',
        width: 120,
        render: (text, record) => {
          return text ? text : '--';
        },
      },
      {
        title: '入池人员',
        dataIndex: 'userName',
        key: 'userName',
        width: 120,
        render: (text, record) => {
          return text ? text : '--';
        },
      },
      {
        title: '可投资额度',
        dataIndex: 'investmentAmounts',
        key: 'investmentAmounts',
        width: 120,
        render: (text, record) => {
          console.log(11111111111111, record);
          if (record.investmentAmountsEdit) {
            return (
              <InputNumberC
                form={this.props.form}
                dataIndex={`investmentAmounts${record.id}`}
                splitStyle={true}
                precision={2}
                initialValue={record.investmentAmounts}
                onChange={(e) => this.changeInvestmentAmounts(e, record)}
              />
            );
          } else {
            return text ? accounting.formatNumber(Number(text), 2) : '--';
          }
        },
      },
      ...(type == '债券'
        ? [
            {
              title: '主体区域',
              dataIndex: 'bodyArea',
              key: 'bodyArea',
              width: 120,
            },
            {
              title: '内部评级',
              dataIndex: 'internalRating',
              key: 'internalRating',
              width: 120,
              render: (text, record) => {
                if (record.internalRatingEdit) {
                  return (
                    <SelectC
                      form={this.props.form}
                      initialValue={record.internalRating == 'null' ? null : record.internalRating}
                      dataIndex={`internalRating${record.id}`}
                      dataSource={this.state.internalRatingData ? this.state.internalRatingData : []}
                      allowClear={true}
                      positionBody={true}
                    />
                  );
                } else {
                  return text && text != 'null' ? text : '--';
                }
              },
            },
          ]
        : []),
      {
        title: '一级标签',
        dataIndex: 'fstLevelTag',
        key: 'fstLevelTag',
        width: 140,
        render: (text, record, index) => {
          return (
            <span title={text} style={{ display: 'inline-block', width: '130px', height: '16px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {text ? text : '--'}
            </span>
          );
        },
      },
      {
        title: '二级标签',
        dataIndex: 'secLevelTag',
        key: 'secLevelTag',
        width: 210,
        render: (text, record, index) => {
          return (
            <span title={text} style={{ display: 'inline-block', width: '200px', height: '16px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {text ? text : '--'}
            </span>
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: operationWidth,
        fixed: 'right',
        operates: [
          {
            title: '入用户池',
            onClick: (record, index) => {
              this.handleAction(record);
            },
            rules: {
              hide: {
                items: [
                  { key: 'type', value: ['user'], relation: ['='] },
                  { key: 'investmentAmountsEdit', value: [true], relation: ['='] },
                  { key: 'internalRatingEdit', value: [true], relation: ['='] },
                ],
                relation: 'or',
              },
            },
          },
          {
            title: '出池', // 资管环境置灰
            onClick: (record, index) => {
              this.outPool(record, zgType);
            },
            rules: {
              hide: {
                items: [
                  { key: 'type', value: ['user'], relation: ['='] },
                  { key: 'investmentAmountsEdit', value: [true], relation: ['='] },
                  { key: 'internalRatingEdit', value: [true], relation: ['='] },
                ],
                relation: 'or',
              },
              disabled:
                isZiGuan && zgType == 'bond'
                  ? { items: [{ key: 'inPoolWay', value: ['zhtyyds123'], relation: ['!='] }] }
                  : { items: [{ key: 'inPoolWay', value: ['manual'], relation: ['!='] }] },
            },
          },
          {
            title: '出用户池',
            onClick: (record, index) => {
              this.deletePool(record);
            },
            rules: {
              hide: {
                items: [
                  { key: 'type', value: ['user'], relation: ['!='] },
                  { key: 'investmentAmountsEdit', value: [true], relation: ['='] },
                  { key: 'internalRatingEdit', value: [true], relation: ['='] },
                ],
                relation: 'or',
              },
              disabled: { items: [{ key: 'userId', value: [`${isUser}`], relation: ['!='] }] },
            },
          },
          {
            title: '修改额度',
            onClick: (record, index) => {
              this.changeLimit(record, 'limit');
            },
            rules: {
              hide: {
                items: [
                  { key: 'inPoolWay', value: ['manual'], relation: ['!='] },
                  { key: 'investmentAmountsEdit', value: [true], relation: ['='] },
                  { key: 'internalRatingEdit', value: [true], relation: ['='] },
                ],
                relation: 'or',
              },
            },
          },
          ...(type == '债券'
            ? [
                {
                  title: '修改内评',
                  onClick: (record, index) => {
                    this.changeLimit(record, 'rating');
                  },
                  rules: {
                    hide: {
                      items: [
                        { key: 'inPoolWay', value: ['manual'], relation: ['!='] },
                        { key: 'internalRatingEdit', value: [true], relation: ['='] },
                        { key: 'investmentAmountsEdit', value: [true], relation: ['='] },
                      ],
                      relation: 'or',
                    },
                  },
                },
              ]
            : []),
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveLimit(record);
            },
            rules: {
              hide: {
                items: [
                  { key: 'investmentAmountsEdit', value: [true], relation: ['!='] },
                  { key: 'internalRatingEdit', value: [true], relation: ['!='] },
                ],
                relation: 'and',
              },
            },
          },
          {
            title: '取消',
            onClick: (record, index) => {
              this.cancelLimit(record);
            },
            rules: {
              hide: {
                items: [
                  { key: 'investmentAmountsEdit', value: [true], relation: ['!='] },
                  { key: 'internalRatingEdit', value: [true], relation: ['!='] },
                ],
                relation: 'and',
              },
            },
          },
        ],
      },
    ];

    this.setState({
      columns,
      fixedColumns: columns,
    });
  };

  // 初始化页面请求后台数据
  getSelectData = (lll, isZiGuan) => {
    const { dispatch } = this.props;
    // 获取券池名称下拉框
    dispatch({
      type: 'couponPoolQueryM/findName',
      payload: {
        assetClassId: lll,
      },
      callback: (res) => {
        this.setState(
          {
            selectName: res.data.dataSource, // 券池名称下拉框内容
            getnewColumns: res.data.columns, //  字段设置内容
          },
          () => this.setWordValue(lll, isZiGuan),
        );
      },
    });

    // 获取Modal框标签
    dispatch({
      type: 'couponPoolQueryM/searchPoolTag',
      payload: { type: lll },
      callback: (res) => {
        const { data } = res;
        const { dataSource } = data;
        this.setState({
          selectPoolTag: dataSource,
        });
      },
    });

    // 获取Modal框券池名称下拉
    dispatch({
      type: 'couponPoolQueryM/searchPoolName',
      payload: {
        assetClass: lll,
      },
      callback: (res) => {
        const { data } = res;
        const { dataSource } = data;
        this.setState({
          selectPoolName: dataSource,
        });
      },
    });

    const {
      globalM: {
        dataDictionary: { SECURITYPOOLITEMSTOCK_DICT = [], SECURITYPOOLITEMFUND_DICT = [], SECURITYPOOLITEMBOND_DICT = [] },
      },
    } = this.props;
    let types = '';
    if (lll == 'stock') {
      types = SECURITYPOOLITEMSTOCK_DICT;
    } else if (lll == 'fund') {
      types = SECURITYPOOLITEMFUND_DICT;
    } else {
      types = SECURITYPOOLITEMBOND_DICT;
    }
    this.setState({
      selectCol: types,
    });
  };

  // 字段设置默认值
  setWordValue = (lll, isZiGuan) => {
    if (lll == 'bond') {
      this.setState(
        {
          selectedKeys: isZiGuan
            ? ['creditRating', 'residualMaturity', 'evalutedYield', 'camsCreditRating', 'innerCreditRating']
            : ['creditRating', 'residualMaturity', 'evalutedYield'],
        },
        () => this.handleOk(),
      );
    } else if (lll == 'stock') {
      this.setState(
        {
          selectedKeys: ['closingprice', 'daychangerate', 'pe'],
        },
        () => this.handleOk(),
      );
    } else if (lll == 'fund') {
      this.setState(
        {
          selectedKeys: ['dailyreturn', 'annualyieldl7d', 'enddate'],
        },
        () => this.handleOk(),
      );
    }
  };

  // 响应出用户池点击
  deletePool = (record) => {
    const { dispatch } = this.props;
    const that = this;
    confirm({
      title: '确认出用户池?',
      onOk() {
        dispatch({
          type: 'couponPoolQueryM/deletePool',
          payload: {
            id: record.id,
          },
        }).then((res) => {
          if (res && res.code == 0) {
            message.success('出池成功');
            that.getTableData();
          } else {
            message.error('出池失败');
          }
        });
      },
    });
  };

  // 获取表格数据
  getTableData = () => {
    const { exportQuery, isZiGuan, columns, sortData, selectName, assetType } = this.state;
    if (isZiGuan) {
      if (assetType == 'bond') {
        const selectNameing = selectName.filter((item) => {
          return item.id == exportQuery.securityPoolId;
        });
        if (selectNameing && selectNameing.length > 0 && selectNameing[0].system) {
          columns.map((item) => {
            if (item.key == 'stockCode') {
              item.render = (text) => <a>{text}</a>;
              item.onCell = (record) => {
                return {
                  onClick: () => {
                    this.superOnClick(record);
                  },
                };
              };
            }
          });
          this.setState({ columns });
        } else {
          columns.map((item) => {
            if (item.key == 'stockCode') {
              item.render = (text, record) => {
                return text ? text : '--';
              };
              item.onCell = (record) => {
                return undefined;
              };
            }
          });
          this.setState({ columns });
        }
      } else if (assetType == 'stock') {
        columns.map((item) => {
          if (item.key == 'stockCode') {
            item.render = (text) => <a>{text}</a>;
            item.onCell = (record) => {
              return {
                onClick: () => {
                  this.superOnClickStock(record);
                },
              };
            };
          }
        });
        this.setState({ columns });
      } else {
        columns.map((item) => {
          if (item.key == 'stockCode') {
            item.render = (text, record) => {
              return text ? text : '--';
            };
            item.onCell = (record) => {
              return undefined;
            };
          }
        });
        this.setState({ columns });
      }
    }
    // 每次查询前清空表格数据
    this.setState({ tableData: [] });
    this.props.dispatch({
      type: 'couponPoolQueryM/findAll',
      payload: { ...exportQuery, sortInfo: JSON.stringify(sortData) == '{}' ? undefined : sortData },
      callback: (res) => {
        if (res) {
          this.setState({
            tableData: res.data.dataSource,
            current: res.data.pageInfo.currentPage,
            pageSize: res.data.pageInfo.numInPage,
            total: res.data.pageInfo.total,
          });
        } else {
          this.setState({
            tableData: [],
            current: 1,
            pageSize: 10,
            total: 0,
          });
        }
      },
    });
  };

  // 响应查询事件
  searchData = (data) => {
    this.setState(
      {
        exportQuery: data,
      },
      () => this.getTableData(),
    );
  };

  // 分页按钮响应事件
  tableChange = (pagination, filt, sorter) => {
    const { exportQuery } = this.state;
    let sortData = {};
    if (JSON.stringify(exportQuery) == '{}') {
      message.error('请先选择查询条件');
      return;
    }
    exportQuery.pageInfo = {
      currentPage: pagination.current,
      numInPage: pagination.pageSize,
    };
    // 操作栏点击不掉接口
    if (sorter.columnKey == 'operate') return;
    if (sorter.order !== undefined) {
      sortData.sortItem = sorter.columnKey;
      if ('descend' == sorter.order) {
        sortData.sortType = 'DESC';
      } else if ('ascend' == sorter.order) {
        sortData.sortType = 'ASC';
      } else {
        sortData = {};
      }
    }

    this.setState(
      {
        exportQuery,
        sortedInfo: sorter,
        sortData,
      },
      () => this.getTableData(),
    );
  };

  // 响应字段设置内checkbox点击
  onSelect = (selectedKeys, info) => {
    this.setState({
      selectedKeys,
    });
  };

  // 响应出池点击
  outPool = (record, type) => {
    // 若在资管环境下，则抛出事件，由调用iframe的外层响应，处理相关逻辑
    if (this.state.isZiGuan) {
      window.parent.postMessage(
        {
          id: record.id, // 标的在库中的唯一标识符
          type, // 标的类型 bond-债券 stock-股票
          securityPoolId: record.securityPoolId, // 券池ID
          stockCode: record.stockCode, // 标的代码
          exchangeCode: record.exchangeCode, // 交易市场
        },
        '*',
      );
    } else {
      // 若在maat环境下，则弹出模态框
      this.setState(
        {
          detailData: record.flowEditVo,
          toolText: record.secLevelTag,
        },
        () => {
          this.setState({
            isVisible: true,
          });
        },
      );
    }
  };

  // 出池model取消
  onCancel = () => {
    this.setState({
      isVisible: false,
    });
  };

  // 出池model提交或保存
  handleOutPool = (e) => {
    const { dispatch } = this.props;
    const newData = this.child.getData();
    const arr = newData;
    if (arr == undefined) return;
    arr.type = e;
    if (arr !== undefined) {
      dispatch({
        type: 'couponPoolApprovalM/checkAdd',
        payload: arr,
        callback: (res) => {
          dispatch({
            type: 'couponPoolApprovalM/getAddAndEdit',
            payload: arr,
            callback: (res) => {
              if (res.code == 0) {
                this.setState({ isVisible: false });
                this.getTableData();
              }
            },
          });
        },
      });
    }
  };

  // 出池组件
  outPoolModal = () => {
    const { isVisible, detailData, toolText } = this.state;
    const { loading } = this.props;
    const type = 'outPool2';
    const newProps = {
      visible: isVisible,
      title: `出池`,
      width: 1300,
      footer: [
        <PrimaryGhostC key='footOne' onClick={this.onCancel} title='取消' />,
        <PrimaryC key='save' onClick={() => this.handleOutPool('0')} style={{ marginLeft: '10px' }} loading={loading.effects['couponPoolApprovalM/getAddAndEdit']} title='保存' />,
        <PrimaryC
          key='commit'
          onClick={() => this.handleOutPool('1')}
          style={{ marginLeft: '10px' }}
          loading={loading.effects['couponPoolApprovalM/getAddAndEdit']}
          title='提交'
        />,
      ],
    };
    return (
      <div>
        {isVisible ? (
          <ModalC {...newProps} onCancel={this.onCancel}>
            <NewModal
              detailData={detailData} // 修改或查看时回填的数据
              type={type} // 是什么操作（新增，查看，编辑，出池，重新发起）
              onRef={(ref) => (this.child = ref)} // 父组件对本组件的引用
              toolText={toolText} // 自动带出标签的文字
            />
          </ModalC>
        ) : null}
      </div>
    );
  };

  // 响应字段设置确定事件
  handleOk = () => {
    this.setState({
      visible: false,
    });
    const { assetType, exportQuery, getnewColumns, selectedKeys, fixedColumns, isZiGuan, selectName, columns } = this.state;
    const datas = getnewColumns;
    const selectDa = selectedKeys;
    const fixColumns = _.cloneDeep(fixedColumns);
    const newAddedColumns = selectDa
      .map((key) => {
        const column = _.find(datas, (item) => item.key === key);
        if (column) {
          return { ...column, dataIndex: key };
        }
        return null;
      })
      .filter(Boolean);
    fixColumns.splice(4, 0, ...newAddedColumns);
    fixColumns.map((item) => {
      if (
        item.key == 'dailyreturn' || // 基金右对齐
        item.key == 'annualyieldl7d' ||
        item.key == 'navyieldl1m' ||
        item.key == 'navyieldl3m' ||
        item.key == 'navyieldl6m' ||
        item.key == 'navyieldl1y' ||
        item.key == 'navyieldfound' || //
        item.key == 'closingprice' || // 股票
        item.key == 'daychangerate' ||
        item.key == 'pe' ||
        item.key == 'turnoverrate' ||
        item.key == 'fmarketval' ||
        item.key == 'basiceps' ||
        item.key == 'bvps' ||
        item.key == 'captitalreserveps' ||
        item.key == 'retainedearningps' ||
        item.key == 'netcashflowoperps' ||
        item.key == 'evalutedYield' || // 债券
        item.key == 'netValuation' ||
        item.key == 'fullvaluationZg' ||
        item.key == 'sybj' ||
        item.key == 'fundassetnet'
      ) {
        item.align = 'right';
      }
      if (isZiGuan) {
        if (assetType == 'bond') {
          const selectNameing = selectName.filter((item) => {
            return item.id == exportQuery.securityPoolId;
          });
          if (selectNameing && selectNameing.length > 0 && selectNameing[0].system) {
            if (item.key == 'stockCode') {
              item.render = (text) => <a>{text}</a>;
              item.onCell = (record) => {
                return {
                  onClick: () => {
                    this.superOnClick(record);
                  },
                };
              };
            }
          } else if (item.key == 'stockCode') {
            item.render = (text, record) => {
              return text ? text : '--';
            };
            item.onCell = (record) => {
              return undefined;
            };
          }
        } else if (assetType == 'stock') {
          if (item.key == 'stockCode') {
            item.render = (text) => <a>{text}</a>;
            item.onCell = (record) => {
              return {
                onClick: () => {
                  this.superOnClickStock(record);
                },
              };
            };
          }
        } else if (item.key == 'stockCode') {
          item.render = (text, record) => {
            return text ? text : '--';
          };
          item.onCell = (record) => {
            return undefined;
          };
        }
      }
    });

    this.setState({
      columns: fixColumns,
    });
  };

  // 股票查询股票代码超链接点击响应
  superOnClickStock = (record) => {
    const payloadRequry = {
      tradingCode: record.stockCode,
      exchangeCode: record.exchangeCode,
      securityPoolId: record.securityPoolId,
    };
    this.props.dispatch({
      type: 'couponPoolQueryM/findSuperData',
      payload: {
        ...payloadRequry,
      },
      callback: (res) => {
        if (res) {
          const zgdataSource = this.dataSourceChange(res.data.dataSource);
          const zgcolumns = this.stockColumnsChange(res.data.columns);
          this.setState({ zgcolumns, zgdataSource });
        } else {
          this.setState({
            zgcolumns: [],
            zgdataSource: [],
          });
        }
      },
    });
    this.setState({ zgModelData: record, zgisShow: true });
  };

  // 超链接点击响应
  superOnClick = (record) => {
    const payloadRequry = {
      tradingCode: record.stockCode,
      exchangeCode: record.exchangeCode,
      securityPoolId: record.securityPoolId,
    };
    this.props.dispatch({
      type: 'couponPoolQueryM/findSuperData',
      payload: {
        ...payloadRequry,
      },
      callback: (res) => {
        if (res) {
          const zgdataSource = this.dataSourceChange(res.data.dataSource);
          const zgcolumns = this.columnsChange(res.data.columns);
          this.setState({ zgcolumns, zgdataSource });
        } else {
          this.setState({
            zgcolumns: [],
            zgdataSource: [],
          });
        }
      },
    });
    this.setState({ zgModelData: record, zgisShow: true });
  };

  // 出入池数据优化
  dataSourceChange = (data) => {
    data.forEach((value) => {
      if (value.direction == 'out') {
        value.direction = (
          <div>
            {' '}
            <img style={{ width: '12px', height: '14px', marginRight: '8px' }} src={upRed}></img>出池
          </div>
        );
      } else if (value.direction == 'in') {
        value.direction = (
          <div>
            <img style={{ width: '12px', height: '14px', marginRight: '8px' }} src={downGreen}></img>入池
          </div>
        );
      }
    });
    return data;
  };

  // 修改投资额度和内部评级
  changeLimit = (record, rowType) => {
    if (this.state.rowId) {
      message.warning('请先保存数据');
      return;
    }
    const { tableData } = this.state;
    const tableDataCopy = _.cloneDeep(tableData);
    tableDataCopy.forEach((item) => {
      if (item.id == record.id) {
        if (rowType == 'limit') {
          item.investmentAmountsEdit = true;
        }
        if (rowType == 'rating') {
          item.internalRatingEdit = true;
        }
      }
      // console.log(tableData,record.id,rowType);
      this.setState({ rowId: record.id, rowType, tableData: tableDataCopy });
    });
  };

  // 投资额度保存和内部评级
  saveLimit = (record) => {
    const { tableData, rowType } = this.state;
    const {
      form: { getFieldValue },
      dispatch,
    } = this.props;
    const query = {};
    let url = '';
    if (rowType == 'limit') {
      query.investmentAmounts = getFieldValue(`investmentAmounts${record.id}`);
      url = 'couponPoolQueryM/saveInvestmentAmounts';
    }
    if (rowType == 'rating') {
      query.bondRating = getFieldValue(`internalRating${record.id}`) == undefined ? null : getFieldValue(`internalRating${record.id}`);
      url = 'couponPoolQueryM/saveInternalRating';
    }
    dispatch({
      type: url,
      payload: {
        id: record.id,
        ...query,
      },
      callback: (res) => {
        if (res) {
          const tableDataCopy = _.cloneDeep(tableData);
          tableDataCopy.forEach((item) => {
            if (item.id == record.id) {
              if (rowType == 'limit') {
                (item.investmentAmountsEdit = false), (item.investmentAmounts = getFieldValue(`investmentAmounts${record.id}`));
              }
              if (rowType == 'rating') {
                (item.internalRatingEdit = false), (item.internalRating = getFieldValue(`internalRating${record.id}`));
              }
            }
          });
          this.setState({ rowId: '', rowType: '', tableData: tableDataCopy });
        }
      },
    });
  };

  // 投资额度取消和内部评级
  cancelLimit = (record) => {
    const { tableData, rowType } = this.state;
    const tableDataCopy = _.cloneDeep(tableData);
    tableDataCopy.forEach((item) => {
      if (item.id == record.id) {
        if (rowType == 'limit') {
          item.investmentAmountsEdit = false;
        }
        if (rowType == 'rating') {
          item.internalRatingEdit = false;
        }
      }
    });
    this.setState({ rowId: '', rowType: '', tableData: tableDataCopy });
  };

  // 出入池首列优化
  columnsChange = (clu) => {
    const result = clu.some((item) => item.key == 'investmentScope');
    if (result) {
      clu.forEach((item) => {
        if (item.key == 'effectiveDate') {
          item.width = '183px';
        }
        if (item.key == 'direction') {
          item.width = '100px';
        }
        if (item.key == 'camsRating' || item.key == 'camsCreditRating') {
          (item.width = '135px'),
            (item.render = (text) => {
              return (
                <span title={text} style={{ display: 'inline-block', width: '125px', height: '16px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {text ? text : '--'}
                </span>
              );
            });
        }
        if (item.key == 'innerRating' || item.key == 'creditRating') {
          (item.width = '190px'),
            (item.render = (text) => {
              return (
                <span title={text} style={{ display: 'inline-block', width: '180px', height: '16px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {text ? text : '--'}
                </span>
              );
            });
        }
        if (item.key == 'investmentScope') {
          item.render = (text) => {
            return (
              <span title={text} style={{ display: 'inline-block', width: '180px', height: '16px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {text ? text : '--'}
              </span>
            );
          };
        }
      });
    } else {
      clu.forEach((item) => {
        if (item.key == 'effectiveDate') {
          item.width = '190px';
        }
        if (item.key == 'direction') {
          item.width = '120px';
        }
        if (item.key == 'innerRating' || item.key == 'creditRating' || item.key == 'camsCreditRating' || item.key == 'camsRating') {
          item.width = '200px';
          item.render = (text) => {
            return (
              <span title={text} style={{ display: 'inline-block', width: '190px', height: '16px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {text ? text : '--'}
              </span>
            );
          };
        }
      });
    }
    if (clu.length && clu[clu.length - 1].title != '操作') {
      clu.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: 65,
        operates: [
          {
            title: '查看',
            onClick: (record, index) => {
              this.viewData(record);
            },
            rules: {
              disabled: { items: [{ key: 'targetId', value: [null], relation: ['='] }] },
            },
          },
        ],
      });
    }
    return clu;
  };

  // 资管股票查询股票代码点击模态框
  stockColumnsChange = (clu) => {
    // 股票查询页面股票代码点击只需要时间和方向列
    const newClu = clu.filter((item) => item.key == 'effectiveDate' || item.key == 'direction');
    if (newClu.length && newClu[newClu.length - 1].title != '操作') {
      newClu.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: 65,
        operates: [
          {
            title: '查看',
            onClick: (record, index) => {
              this.detailsData(record);
            },
            rules: {
              disabled: { items: [{ key: 'targetId', value: [null], relation: ['='] }] },
            },
          },
        ],
      });
    }
    return newClu;
  };

  viewData = (record) => {
    window.parent.postMessage(
      {
        id: record.targetId,
        inPoolWay: record.inPoolWay,
        poolName: this.state.exportQuery?.securityPoolId,
      },
      '*',
    );
  };

  detailsData = (record) => {
    window.parent.postMessage(
      {
        id: record.targetId,
        type: 'stockDetail',
      },
      '*',
    );
  };

  // 资管环境常规库、私募产品库、高息债券库模态框
  showZiGuanModal = () => {
    const { zgisShow, zgModelData } = this.state;
    const { loading } = this.props;
    const modalProps = {
      destroyOnClose: true,
      visible: zgisShow,
      maskClosable: false,
      footer: null,
      title: `${zgModelData.stockCode}-${zgModelData.stockName}出入${zgModelData.securityPoolName}记录`,
      width: 1200,
      height: 276,
    };

    return (
      <ModalC {...modalProps} onCancel={this.zghandleCancel}>
        <TableC
          columns={this.state.zgcolumns}
          loading={loading.effects['couponPoolQueryM/findSuperData']}
          scroll={{ y: '231px' }}
          dataSource={this.state.zgdataSource}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };

  // 响应字段设置点击改变
  handleVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  // 处理字段设置下拉数据
  changeTreeData = (data) => {
    const arr = [];
    data && data.length
      ? data.map((item) => {
          const newData = {};
          newData.title = item.value;
          newData.key = item.code;
          newData.children = item.children ? this.changeTreeData(item.children) : '';
          arr.push(newData);
        })
      : null;
    return arr;
  };

  // 响应字段设置取消
  cancelAction = () => {
    this.setState({
      visible: false,
    });
  };

  // 响应导出点击事件
  exportFile = () => {
    const { exportQuery } = this.state;
    const obj = _.cloneDeep(exportQuery);
    delete obj.pageInfo;
    if (obj) {
      for (const key in obj) {
        if (Array.isArray(obj[key])) {
          obj[key] = obj[key].join(',');
          if (!obj[key]) delete obj[key]; // 如果是空字符 则删除
        }
      }
    }
    exportFileFunc('gateway/portfolio-server/SecurityPoolItem/export', obj);
  };

  // 字段加排序按钮
  changeColumns = (columns) => {
    const { sortedInfo } = this.state;
    if (columns && columns.length) {
      columns.map((item) => {
        if (item.key != 'operate') {
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == item.key && sortedInfo.order;
        }
        if (!item.width) {
          item.width = 140;
        }
      });
    }

    return columns;
  };

  // 表格展示
  showTable = () => {
    const { loading } = this.props;
    const { selectCol, exportQuery, columns, securityPoolName, selectedKeys, isZiGuan, assetType, rowId } = this.state;
    const treeDatas = this.changeTreeData(selectCol);
    let columnss = this.changeColumns(columns);
    // 在资管环境中当券池为公募类权益策略产品可转债可交换债库或非公募类权益策略产品可转债可交换债库时，不展示内部主体评级和内部债券评级
    if (isZiGuan && assetType == 'bond') {
      if (securityPoolName == '公募类权益策略产品可转债可交换债库' || securityPoolName == '非公募类权益策略产品可转债可交换债库') {
        columnss = columnss.filter((x) => x.key != 'innerCreditRating' && x.key != 'innerRating');
        treeDatas[0].children = treeDatas[0]?.children?.filter((x) => x.key != 'innerCreditRating' && x.key != 'innerRating');
      }
    }
    const content = (
      <div>
        <Spin spinning={this.props.loading.effects['couponPoolQueryM/findCol'] == true}>
          <Tree treeData={treeDatas} checkable={true} defaultExpandAll={true} checkedKeys={{ checked: selectedKeys, halfChecked: [] }} onCheck={this.onSelect} />
        </Spin>
        <div className='btnArea'>
          <div className='btnCol'>
            <Button onClick={this.cancelAction} className='reset-button ' style={{ marginLeft: '56px' }}>
              取消
            </Button>
            <Button onClick={this.handleOk} className='search-button ' style={{ marginLeft: '11px' }}>
              确定
            </Button>
          </div>
        </div>
      </div>
    );
    console.log(11111111, this.state.tableData);
    return (
      <div style={{ marginTop: '10px' }}>
        <Row className={styles.btn}>
          <Col span={12}>
            <Popover
              placement='bottomLeft'
              content={content}
              trigger='click'
              visible={this.state.visible}
              overlayClassName={styles.shstyle}
              onVisibleChange={this.handleVisibleChange}
              style={{ height: '317px', width: '240px' }}
            >
              <PrimaryC title='字段设置' helper='可自定义选择展示的字段' style={{ marginBottom: '10px' }} />
            </Popover>
          </Col>
          <Col span={12}>
            <PrimaryGhostC title='导出' onClick={this.exportFile} style={{ marginBottom: '10px' }} disabled={JSON.stringify(exportQuery) == '{}'} />
          </Col>
        </Row>
        <TableC
          columns={columnss}
          loading={loading.effects['couponPoolQueryM/findAll']}
          selfScrollY={true}
          scroll={{ x: 'max-content' }}
          dataSource={this.state.tableData}
          current={this.state.current}
          pageSize={this.state.pageSize}
          total={this.state.total}
          rowKey='id'
          pagination={true}
          onChange={this.tableChange}
          rowClassName={(record, index) => {
            // 添加类名作用：保证表格不出现错位
            return record.id === rowId ? 'investmentAmounts-select' : '';
          }}
        />
      </div>
    );
  };

  // 响应入用户池点击
  handleAction = (record) => {
    this.setState({
      isShow: true,
      InpoolData: record,
    });
  };

  // 入用户池modal框的确定操作
  handlaOk1 = () => {
    const { InpoolData } = this.state;
    const securityPoolId = this.enterUserPool.props.form.getFieldValue('name1a');
    const userPool = {
      stockCode: InpoolData.stockCode,
      exchangeCode: InpoolData.exchangeCode,
      securityPoolId,
      tag: this.state.title2,
      internalRating: InpoolData.internalRating,
      bodyArea: InpoolData.bodyArea,
      bondType: InpoolData.bondType,
      investmentAmounts: InpoolData.investmentAmounts,
    };
    if (securityPoolId == undefined) {
      message.error('请输入券池名称');
    } else {
      this.props.dispatch({
        type: 'couponPoolQueryM/addPool',
        payload: userPool,
        callback: (res) => {
          if (res) {
            this.setState({
              isShow: false,
            });
            this.getTableData();
          }
        },
      });
    }
  };

  // 入用户池model框取消
  handleCancel = () => {
    this.setState({
      isShow: false,
    });
  };

  // 资管model框取消
  zghandleCancel = () => {
    this.setState({ zgisShow: false });
  };

  // 入用户池model框标签内容
  changTage = (newTag2) => {
    this.setState({
      title2: newTag2,
    });
  };

  // 入用户池model框
  showModal = () => {
    const { isShow, selectPoolName, selectPoolTag } = this.state;
    const modalProps = {
      destroyOnClose: true,
      visible: isShow,
      maskClosable: false,
      title: '入用户池',
      width: 380,
      confirmLoading: this.props.loading.effects['couponPoolQueryM/addPool'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.handlaOk1} onCancel={this.handleCancel}>
        <EnterUserPool selectPoolName={selectPoolName} selectPoolTag={selectPoolTag} changTage={this.changTage} onRef={(ref) => (this.enterUserPool = ref)} />
      </ModalC>
    );
  };

  // 响应重置
  onClear = () => {
    this.setState({ current: 1, pageSize: 10, total: '', tableData: [], exportQuery: {} });
  };

  // 清空表格数据
  clearTable = () => {
    this.setState({ tableData: [] });
  };

  // 获得券池名称
  gteSecurityPoolName = (e) => {
    this.setState({ securityPoolName: e });
  };

  render() {
    const { selectName, typeName, selectPoolTag, isZiGuan } = this.state;
    return (
      <ContentPackage
        title={`${typeName}`}
        contentHtml={
          <div className={styles.shstyle}>
            <div className='bondDeviation'>
              <div style={{ marginBottom: '10px' }}>
                <QueryC
                  onQuery={this.searchData}
                  onClear={this.onClear}
                  clearTable={this.clearTable}
                  selectName={selectName}
                  selectPoolTag={selectPoolTag}
                  isZiGuan={isZiGuan}
                  gteSecurityPoolName={this.gteSecurityPoolName}
                />
              </div>
              {this.showTable()}
              {this.showModal()}
              {this.outPoolModal()}
              {this.showZiGuanModal()}
            </div>
          </div>
        }
      />
    );
  }
}
